package com.ebt.m.cloud;

import android.content.Context;

import com.ebt.m.cloud.bean.MyBusinessInfLocal;
import com.ebt.m.cloud.bean.MyBusinessInfo;
import com.ebt.m.cloud.db.DBController;
import com.ebt.m.cloud.downloader.DownloadService;
import com.ebt.m.cloud.downloader.callback.DownloadManager;
import com.ebt.m.cloud.downloader.domain.DownloadInfo;
import com.ebt.m.utils.ConfigData;

import java.io.File;
import java.sql.SQLException;

/**
 * Created by Damon.Han on 2018/5/30 0030.
 *
 * @author Damon
 */
public class DownLoader {

    private Context context;
    private static DownloadManager downloadManager;

    public DownLoader(Context context) {
        this.context = context;
        downloadManager = DownloadService.getDownloadManager(context.getApplicationContext());
    }

    /**
     * 下载
     *
     * @param data
     */
    public void beginDownload(int id, MyBusinessInfo data) {
        DownloadInfo downloadInfo = downloadManager.getDownloadById(data.getUrl().hashCode());
        File d = new File(ConfigData.CACHE_PATH);
        if (!d.exists()) {
            d.mkdirs();
        }
        String nameWithSuffix = data.getName();
        if (nameWithSuffix!=null&&nameWithSuffix.contains(".")){
            nameWithSuffix=nameWithSuffix.replace(nameWithSuffix.substring(nameWithSuffix.lastIndexOf("."),nameWithSuffix.length()),".data");
        }
        String path = d.getAbsolutePath().concat("/").concat(id + "_").concat(nameWithSuffix);
        downloadInfo = new DownloadInfo.Builder().setSourceId(id).setUrl(data.getUrl()).setPath(path).build();
        downloadManager.download(downloadInfo);
        //save extra info to my database.
        MyBusinessInfLocal myBusinessInfLocal = new MyBusinessInfLocal(data.getUrl().hashCode(), data.getName(), data.getIcon(), data.getUrl());
        try {
            DBController dbController = DBController.getInstance();
            dbController.createOrUpdateMyDownloadInfo(myBusinessInfLocal);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
